<template>
	<view class="cart-container page-container-with-bottom-btn">

		<view class="cart-content" v-if="cartList.length > 0">
			<!-- 商品数量统计 -->
			<view class="cart-header">
				<text class="cart-count">共{{ cartList.length }}件商品</text>
				<view class="header-divider"></view>
			</view>

			<!-- 购物车列表 -->
			<u-checkbox-group>
				<view class="cart-list">
					<view class="cart-item" v-for="(item, index) in cartList" :key="index">
						<view class="item-checkbox">
							<u-checkbox :checked="item.checked" @change="onItemCheck(index)" active-color="#1c705e"
								:name="'item_' + index"></u-checkbox>
						</view>
						<view class="item-image">
							<image :src="$tools.buildUrl(item.main_image)" mode="aspectFill" class="product-image">
							</image>
						</view>
						<view class="item-info">
							<text class="product-name">{{ item.spu_name }}</text>
							<text class="product-spec">{{ item.sku_name }}</text>
							<view class="product-price">
								<text class="price-symbol">¥</text>
								<text class="price-value">{{ item.actual_price }}</text>
							</view>
						</view>
						<view class="item-right">
							<view class="quantity-control">
								<view class="quantity-btn" @click="decreaseQuantity(index)">
									<u-icon name="minus" size="12" color="#666"></u-icon>
								</view>
								<input class="quantity-input" type="number" :value="item.quantity"
									@input="onQuantityInput($event, index)" />
								<view class="quantity-btn" @click="increaseQuantity(index)">
									<u-icon name="plus" size="12" color="#666"></u-icon>
								</view>
							</view>
						</view>
						<view class="item-delete" @click="deleteItem(index)">
							<u-icon name="trash" size="18" color="#999"></u-icon>
						</view>
					</view>
				</view>
			</u-checkbox-group>
		</view>

		<!-- 空购物车 -->
		<view class="empty-cart" v-else>
			<image :src="$tools.buildUrl(shopLogo)" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">购物车还是空的</text>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer fixed-bottom-safe" v-if="cartList.length > 0">
			<view class="footer-left">
				<view class="select-all">
					<u-checkbox-group>
						<u-checkbox :checked="selectAll" @change="onSelectAll" active-color="#1c705e"
							name="selectAll"></u-checkbox>
					</u-checkbox-group>
					<text class="select-all-text">全选</text>
				</view>
				<view class="total-info">
					<text class="total-text">合计：</text>
					<text class="total-price">¥{{ totalPrice }}</text>
				</view>
			</view>
			<view class="footer-right">
				<button class="checkout-btn" :class="{ disabled: selectedCount === 0 }" @click="checkout">
					结算({{ selectedCount }})
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				cartList: [],
				shopLogo: '/static/images/logo.png'
			}
		},
		computed: {
			...mapGetters(['isLogin', 'openid', 'directid', 'dealerInfo']),

			// 全选状态
			selectAll() {
				return this.cartList.length > 0 && this.cartList.every(item => item.checked)
			},
			// 选中商品数量
			selectedCount() {
				return this.cartList.filter(item => item.checked).length
			},
			// 总价
			totalPrice() {
				return this.cartList
					.filter(item => item.checked)
					.reduce((total, item) => {
						return total + parseFloat(item.actual_price) * item.quantity
					}, 0)
					.toFixed(2)
			}
		},
		onLoad(options) {
			if (this.dealerInfo && this.dealerInfo.shop_logo && this.dealerInfo.shop_logo !== '') {
				this.shopLogo = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			}
			// this.onSearch()
		},
		onShow() {
			this.onSearch()
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.cartList = []
				this.loadDataList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.loadDataList()
				}, 500)
			}
		},
		methods: {
			onSearch() {
				this.page = 1
				this.recordCount = 0
				this.cartList = []
				this.loadDataList()
			},
			loadDataList() {
				if (this.hasSearched) {
					return false
				}

				this.hasSearched = true
				this.$api.order.GetShoppingCartList({
					page: this.page,
					limit: this.limit
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					res.data.forEach(item => {
						item.checked = false
					})
					this.cartList = this.cartList.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},
			// 单项选择
			onItemCheck(index) {
				this.cartList[index].checked = !this.cartList[index].checked
				this.$forceUpdate()
			},
			// 全选/取消全选
			onSelectAll() {
				const newSelectAll = !this.selectAll
				this.cartList.forEach(item => {
					item.checked = newSelectAll
				})
				this.$forceUpdate()
			},
			// 减少数量
			decreaseQuantity(index) {
				if (this.cartList[index].quantity > 1) {
					this.cartList[index].quantity--
					this.updateItem(this.cartList[index])
				}
			},
			// 增加数量
			increaseQuantity(index) {
				this.cartList[index].quantity++
				this.updateItem(this.cartList[index])
			},
			// 数量输入
			onQuantityInput(event, index) {
				const value = parseInt(event.detail.value) || 1
				this.cartList[index].quantity = Math.max(1, value)
				this.updateItem(this.cartList[index])
			},
			// 更新商品数量
			updateItem(item) {
				this.$api.order.EditShoppingCart(item).then(res => {
					// uni.showToast({
					// 	title: res.msg,
					// 	icon: 'success'
					// })
				})
			},
			// 删除商品
			deleteItem(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.$api.order.DelShoppingCart({
								id: this.cartList[index].id
							}).then(res => {
								this.cartList.splice(index, 1)
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
							})
						}
					}
				})
			},
			// 去购物
			goShopping() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			// 结算
			checkout() {
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					})
					return
				}

				const selectedItems = this.cartList.filter(item => item.checked)
				const cart_ids = selectedItems.map(item => item.id).join(',')
				// 这里可以将选中的商品信息传递给订单页面
				uni.navigateTo({
					url: '/pages/order/payment?cart_ids=' + cart_ids
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cart-container {
		background-color: #f8f8f8;
	}

	.cart-content {
		padding: 20rpx;
	}

	.cart-header {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 16rpx;
	}

	.cart-count {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}

	.header-divider {
		height: 2rpx;
		background-color: #1c705e;
		margin-top: 20rpx;
	}

	.cart-list {
		background-color: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.cart-item:last-child {
		border-bottom: none;
	}

	.item-checkbox {
		margin-right: 20rpx;
	}

	.item-image {
		margin-right: 20rpx;
	}

	.product-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.item-info {
		flex: 1;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 100%;
	}

	.product-spec {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 12rpx;
		display: block;
	}

	.item-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-right: 20rpx;
	}

	.product-price {
		display: flex;
		align-items: baseline;
	}

	.price-symbol {
		font-size: 24rpx;
		color: #1c705e;
	}

	.price-value {
		font-size: 32rpx;
		font-weight: bold;
		color: #1c705e;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		border: 2rpx solid #e5e5e5;
		border-radius: 8rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f8f8f8;
	}

	.quantity-input {
		width: 80rpx;
		height: 60rpx;
		text-align: center;
		font-size: 28rpx;
		border: none;
		background-color: #ffffff;
	}

	.item-delete {
		padding: 10rpx;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 40rpx;
	}

	.empty-image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 40rpx;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 60rpx;
	}

	.go-shopping-btn {
		background-color: #1c705e;
		color: #ffffff;
		border: none;
		border-radius: 40rpx;
		padding: 20rpx 60rpx;
		font-size: 28rpx;
	}

	.cart-footer {
		border-top: 2rpx solid #e5e5e5;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.footer-left {
		display: flex;
		align-items: center;
	}

	.select-all {
		display: flex;
		align-items: center;
		margin-right: 40rpx;
	}

	.select-all-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 10rpx;
	}

	.total-info {
		display: flex;
		align-items: baseline;
	}

	.total-text {
		font-size: 28rpx;
		color: #333;
	}

	.total-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #1c705e;
	}

	.checkout-btn {
		background-color: #1c705e;
		color: #ffffff;
		border: none;
		border-radius: 40rpx;
		padding: 0rpx 40rpx;
		font-size: 28rpx;
	}

	.checkout-btn.disabled {
		background-color: #ccc;
	}
</style>